# Fetch roster item nickname(s) from vCard and set roster label(s)

namespace eval fetch_nickname {}

proc fetch_nickname::service_request {connid service} {
    foreach jid [::roster::get_jids $connid] {
	if {[server_from_jid $jid] == [server_from_jid $service]} {
	    user_request $connid $jid
	}
    }
}

proc fetch_nickname::user_request {connid jid} {
    jlib::send_iq get \
	[jlib::wrapper:createtag vCard \
	     -vars [list xmlns vcard-temp]] \
	-to $jid \
	-connection $connid \
	-command [list [namespace current]::parse_result $connid $jid]
}

proc fetch_nickname::parse_result {connid jid res child} {
    if {$res != "OK"} return

    jlib::wrapper:splitxml $child tag vars isempty chdata children

    foreach item $children {
	userinfo::parse_vcard_item $jid $item
    }

    if {[info exists ::userinfo::userinfo(nickname,$jid)] && \
	    ![cequal $::userinfo::userinfo(nickname,$jid) ""]} {
	roster::itemconfig $connid $jid \
			   -name $::userinfo::userinfo(nickname,$jid)
	roster::send_item $connid $jid
    }
}

proc fetch_nickname::add_user_menu {m connid jid} {
    set rjid [roster::find_jid $connid $jid]
    if {$rjid == ""} {
	set state disabled
    } else {
	set state normal
    }
    $m add command -label [::msgcat::mc "Fetch nickname"] \
	-command [list [namespace current]::user_request $connid $rjid] \
	-state $state
}

hook::add chat_create_user_menu_hook \
    [namespace current]::fetch_nickname::add_user_menu 73
hook::add roster_jid_popup_menu_hook \
    [namespace current]::fetch_nickname::add_user_menu 73

proc fetch_nickname::add_service_menu {m connid jid} {
    set rjid [roster::find_jid $connid $jid]
    if {$rjid == ""} {
	set state disabled
    } else {
	set state normal
    }
    $m add command -label [::msgcat::mc "Fetch user nicknames"] \
	-command [list [namespace current]::service_request $connid $rjid] \
	-state $state
}

hook::add roster_service_popup_menu_hook \
    [namespace current]::fetch_nickname::add_service_menu 73

